package com.yuerlive.rainbow.module.live.adapter;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.netease.nimlib.sdk.chatroom.constant.MemberType;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomMessage;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomMessageExtension;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomNotificationAttachment;
import com.netease.nimlib.sdk.msg.attachment.MsgAttachment;
import com.netease.nimlib.sdk.msg.attachment.NotificationAttachment;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.nimlib.sdk.msg.constant.NotificationType;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.yuerlive.rainbow.R;
import com.yuerlive.rainbow.RainbowApp;
import com.yuerlive.rainbow.entity.User;
import com.yuerlive.rainbow.nim.CustomMessage;
import com.yuerlive.rainbow.nim.GiftAttachment;
import com.yuerlive.rainbow.nim.NimHelper;
import com.yuerlive.rainbow.utils.DeviceUtils;
import com.yuerlive.rainbow.utils.DownloadImage;
import com.yuerlive.rainbow.utils.L;
import com.yuerlive.rainbow.utils.UserProxy;
import com.yuerlive.rainbow.widget.timeselector.TextUtil;

import java.util.List;
import java.util.Map;

import static com.netease.nimlib.sdk.msg.constant.NotificationType.ChatRoomMemberIn;
import static com.netease.nimlib.sdk.msg.constant.NotificationType.ChatRoomMemberTempMuteAdd;
import static com.netease.nimlib.sdk.msg.constant.NotificationType.ChatRoomMemberTempMuteRemove;

/**
 * Created by xiaoyi on 2017/5/24.
 */

public class ChatItemAdapter extends BaseAdapter {
    private List<Object> messages;
    private Context context;
    private LayoutInflater inflater;

    private CommentOnClickListener listener;

    public interface CommentOnClickListener {
        void commentHandle(IMMessage message);
    }

    public ChatItemAdapter(List<Object> messages, Context context, CommentOnClickListener listener) {
        this.messages = messages;
        this.context = context;
        this.listener = listener;
        this.inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return messages.size();
    }

    @Override
    public Object getItem(int position) {
        return messages.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.message_item, parent, false);
        }
        TextView tvMessage = (TextView) convertView.findViewById(R.id.tvMessage);
        TextView tvLevel = (TextView) convertView.findViewById(R.id.tvLevel);
        Object o = messages.get(position);
        if (o instanceof CustomMessage) {//字符串
            switch (((CustomMessage) o).msgType) {
                case SYSTEM:
                    tvMessage.setTextColor(context.getResources().getColor(R.color.chat_system));
                    tvMessage.setText(((CustomMessage) o).getContent());
                    tvLevel.setVisibility(View.GONE);
                    break;
            }
        } else if (o instanceof ChatRoomMessage) {//云信消息
            tvLevel.setVisibility(View.VISIBLE);
            String nickname = getNickName((ChatRoomMessage) messages.get(position));
            boolean isCustomNotify = hasSystemTag((ChatRoomMessage) messages.get(position));
            if (isCustomNotify) {  //自定义通知
                tvMessage.setTextColor(context.getResources().getColor(R.color.chat_system));
                tvMessage.setText(((ChatRoomMessage) o).getContent());
                tvLevel.setVisibility(View.GONE);
            } else {
                initMessageItem((ChatRoomMessage) messages.get(position), tvMessage, tvLevel, nickname);
            }
        }
        return convertView;
    }

    private boolean hasSystemTag(ChatRoomMessage message) {
        Map<String, Object> ex = message.getRemoteExtension();
        if (ex == null) return false;
        if (ex.containsKey("system")) {
            return true;
        }
        return false;
    }


    private void initMessageItem(ChatRoomMessage message, TextView tvMessage, TextView tvLevel, String nickname) {
        String content = message.getContent();  //消息内容
        MsgAttachment attachment = message.getAttachment();  //消息附加
        int level = 0;
        if (message.getRemoteExtension() != null) {
            if (message.getRemoteExtension().containsKey("level")) {
                level = (int) message.getRemoteExtension().get("level");
                setBadge(tvLevel, level);
                tvLevel.setText(String.valueOf(level));
            }
        }
        if (attachment != null && attachment instanceof ChatRoomNotificationAttachment) {
            ChatRoomNotificationAttachment noAttach = (ChatRoomNotificationAttachment) attachment;
            if (noAttach.getExtension() != null && noAttach.getExtension().containsKey("level")) {
                level = (int) noAttach.getExtension().get("level");
                setBadge(tvLevel, level);
                tvLevel.setText(String.valueOf(level));
            }
        }
        if (content == null) {   //content为空 表示 送礼物 进入聊天室
            if (message.getMsgType() == MsgTypeEnum.notification) {
                if (attachment != null && attachment instanceof ChatRoomNotificationAttachment) {
                    tvLevel.setVisibility(View.GONE);
                    handleNotification((ChatRoomNotificationAttachment) attachment, tvMessage, message, nickname, tvLevel);
                } else {
                    tvMessage.setText(Html.fromHtml(context.getResources().getString(R.string.format_live_notify_enter_other, nickname)));
                    int padding = DeviceUtils.dp2px(RainbowApp.getContext(), 2);
                    tvMessage.setCompoundDrawablePadding(padding);
                    tvLevel.setVisibility(View.VISIBLE);
                }
            } else {
                if (attachment != null && attachment instanceof GiftAttachment) {
                    initGiftMsg(message, tvMessage, nickname);
                }
            }
        } else {  //content 不为空 表示发消息，机器人进入（伪  实际也是发消息）
            Map<String, Object> extension = message.getRemoteExtension();
            if (extension != null) {
                for (Map.Entry<String, Object> entry : extension.entrySet()) {
                    L.e("TAG", "-----------------map------------------------\n" + entry.getKey() + "----------" + entry.getValue());
                }
            }
            tvMessage.setCompoundDrawables(null, null, null, null);
            if (content.startsWith("欢迎") && content.endsWith("进入直播间")) {
                content = content.replace("欢迎", "");
                content = content.replace("进入直播间", "");
                tvMessage.setText(Html.fromHtml(context.getResources().getString(R.string.format_live_notify_enter_other, content)));
                tvLevel.setVisibility(View.VISIBLE);
            } else {
                tvLevel.setVisibility(View.VISIBLE);
                Spanned contentSpan = Html.fromHtml(context.getResources().getString(R.string.format_live_message_role, "" + nickname, "" + content));
                tvMessage.setText(contentSpan);
                tvLevel.setText(String.valueOf(level));
                setBadge(tvLevel, level);
            }
            tvMessage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    User u = UserProxy.getUser();
                    if (listener != null && u != null && !nickname.equals(u.getUserInfo().getNickname())) {
                        listener.commentHandle(message);
                    }
                }
            });
        }

    }

    private void handleNotification(ChatRoomNotificationAttachment attachment, TextView tv, IMMessage message, String nick, TextView tvLevel) {
        if (attachment.getType() == ChatRoomMemberTempMuteAdd) {
            String targetName = attachment.getTargetNicks().get(0);
            if (TextUtils.isEmpty(targetName)) {
                targetName = ((ChatRoomNotificationAttachment) message.getAttachment()).getExtension().get("nickname").toString();
            }

            tv.setText(Html.fromHtml(context.getString(R.string.format_chatroom_mute, targetName)
                    /*, new Html.ImageGetter() {
                        @Override
                        public Drawable getDrawable(String source) {
                            int id = context.getResources().getIdentifier(source, "drawable", context.getPackageName());
                            Drawable drawable = context.getResources().getDrawable(id);
                            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                            return drawable;
                        }
                    }, null*/
            ));
            tv.setCompoundDrawables(null, null, null, null);
        } else if (attachment.getType() == ChatRoomMemberTempMuteRemove) {
            String targetName = attachment.getTargetNicks().get(0);
            String operator = attachment.getExtension().get("ext").toString();
            tv.setText(Html.fromHtml(context.getString(R.string.format_chatroom_mute_remove, targetName, operator)
                    , new Html.ImageGetter() {
                        @Override
                        public Drawable getDrawable(String source) {
                            int id = context.getResources().getIdentifier(source, "drawable", context.getPackageName());
                            Drawable drawable = context.getResources().getDrawable(id);
                            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                            return drawable;
                        }
                    }, null
            ));
            tv.setCompoundDrawables(null, null, null, null);
        } else if (attachment.getType() == ChatRoomMemberIn) {
            tv.setText(Html.fromHtml(context.getResources().getString(R.string.format_live_notify_enter_other, nick)));
            Drawable d = context.getResources().getDrawable(R.drawable.icon_notice);
            d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
            tv.setCompoundDrawables(null, null, null, null);
            int padding = DeviceUtils.dp2px(RainbowApp.getContext(), 2);
            tv.setCompoundDrawablePadding(padding);
            tvLevel.setVisibility(View.VISIBLE);
        } else if (attachment.getType() == NotificationType.ChatRoomManagerAdd) {
            String nickName = message.getLocalExtension().get("target").toString();
            Drawable d = context.getResources().getDrawable(R.drawable.icon_notice);
            d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
            ImageSpan is = new ImageSpan(d, ImageSpan.ALIGN_BOTTOM);
            Spanned contentSpan = Html.fromHtml(context.getResources().getString(R.string.format_live_add_manager, "" + nickName));
            SpannableStringBuilder sb = SpannableStringBuilder.valueOf(contentSpan);
            sb.setSpan(is, 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            tv.setText(sb);
        }
    }

    private void initGiftMsg(IMMessage message, TextView tv, String nickname) {
        GiftAttachment attcachment = (GiftAttachment) message.getAttachment();
        String strGiftMessage;
        String senderName = nickname + "";
        String giftName = attcachment.getGiftName() + " ";

        String giftNumStr = "";
        String giftUrl = attcachment.getGiftShowImage();
        if (!TextUtils.isEmpty(attcachment.getGiftNum())) {
            int giftNum = Integer.parseInt(attcachment.getGiftNum());
            if (giftNum > 1) {
                //adbgiftNumStr = " x" + attcachment.getGiftNum();
            }
        }
        strGiftMessage = "           " + senderName + "： 送出了一个" + giftName + "G" + giftNumStr;
        SpannableStringBuilder builder = new SpannableStringBuilder(strGiftMessage);
        ForegroundColorSpan nickColor = new ForegroundColorSpan(context.getResources().getColor(R.color.chat_nick));
        ForegroundColorSpan messageColor = new ForegroundColorSpan(context.getResources().getColor(R.color.chat_gift));
        ForegroundColorSpan giftNumColor = new ForegroundColorSpan(context.getResources().getColor(R.color.chat_gift));
        builder.setSpan(nickColor, 0, 11 + senderName.length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        builder.setSpan(messageColor, 11 + senderName.length() + 1, 11 + senderName.length() + 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        builder.setSpan(giftNumColor, 11 + senderName.length() + 7, strGiftMessage.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        Drawable gift = new BitmapDrawable(context.getResources(), DownloadImage.getInstance().getBitmap(giftUrl));
        int size = DeviceUtils.dp2px(context, 11);
        gift.setBounds(0, 0, size, size);
        ImageSpan imageSpan = new ImageSpan(gift, ImageSpan.ALIGN_BASELINE);
        builder.setSpan(imageSpan, 11 + senderName.length() + 6 + giftName.length(),
                11 + senderName.length() + 6 + giftName.length() + 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        tv.setText(builder);
    }


    private String getNickName(ChatRoomMessage message) {

        String nickname = null;
        if (TextUtils.isEmpty(nickname)) {
            if (message.getAttachment() instanceof NotificationAttachment) {
                ChatRoomNotificationAttachment attachment = (ChatRoomNotificationAttachment) message.getAttachment();
                nickname = attachment.getOperatorNick();
            }
        }
        if (TextUtil.isEmpty(nickname)) {
            nickname = message.getFromNick();
        }
        if (TextUtil.isEmpty(nickname)) {
            ChatRoomMessageExtension ce = message.getChatRoomMessageExtension();
            if (ce != null) {
                nickname = ce.getSenderNick();
            }
        }
        if (TextUtil.isEmpty(nickname)) {
            ChatRoomMessageExtension ce = message.getChatRoomMessageExtension();
            if (ce != null) {
                nickname = ce.getSenderNick();
            }
        }
        if (TextUtils.isEmpty(nickname)) {
            if (message.getRemoteExtension() != null) {
                try {
                    if (message.getRemoteExtension().containsKey("nickname"))
                        nickname = message.getRemoteExtension().get("nickname").toString();
                } catch (Exception e) {
                    // e.printStackTrace();
                }
            }
        }
        if (TextUtil.isEmpty(nickname)) {
            if (message.getLocalExtension() != null && message.getLocalExtension().containsKey("target"))
                nickname = message.getLocalExtension().get("target").toString();
        }

        if (message.getFromAccount().replaceAll("test_", "").equals(UserProxy.getUser().getUserId())) {
            nickname = UserProxy.getUser().getUserInfo().getNickname();
        }
        if (TextUtil.isEmpty(nickname)) {
            nickname = UserProxy.getUser().getUserInfo().getNickname();
        }
        return nickname;
    }

    private void setBadge(View v, int level) {
        if (level <= 1) {
            v.setBackgroundResource(R.drawable.badge_1);
        } else if (level > 1 && level <= 12) {
            v.setBackgroundResource(R.drawable.badge_2);
        } else if (level > 12 && level <= 22) {
            v.setBackgroundResource(R.drawable.badge_3);
        } else {
            v.setBackgroundResource(R.drawable.badge_4);
        }
    }

}
